package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class EmployeeRealm extends AuthorizingRealm{

    private IEmployeeService employeeService;

    private IRoleService roleService;

    private IPermissionService permissionService;

    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }

    public void setPermissionService(IPermissionService permissionService) {
        this.permissionService = permissionService;
    }

    public void setEmployeeService(IEmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    //根据已登录员工提供角色权限数据
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //认证存的是什么类型就强转成什么类型
        //获取授权员工
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (employee.isAdmin()){
            info.addRole("Admin");
            info.addStringPermission("*:*");
            return info;
        }

        //若不是超管,就根据员工id去数据库查询他的角色和权限
        List<String> roleSns = roleService.selectRoleSnByEmployeeId(employee.getId());
        List<String> expressions = permissionService.selectByEmployeeId(employee.getId());
        info.addRoles(roleSns);
        info.addStringPermissions(expressions);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();

        Employee employee = employeeService.queryEmployeeByUsername(username);
        if(employee!=null){
            //第二个参数是数据库中该用户的密码,shiro完成密码比对
            return new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getName()),this.getName());
        }
        return null;
    }
}
